<template>
  <div ref="chart" style="height: 100%;width: 100%" />
</template>

<script>
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
export default {
  name: 'ECharts',
  props: {
    options: {
      type: Object,
      required: true
    },
    data: {
      type: Function
    }
  },
  data() {
    return {
      chart: null,
      localOption: null,
      localDataset: null
    }
  },
  watch: {
    localDataset() {
      this.chart.setOption(this.localDataset)
    }
  },
  created() {
    this.localOption = this.options
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chart)
    this.chart.setOption(this.localOption)
    const erd = elementResizeDetectorMaker()
    erd.listenTo(this.$refs.chart, element => {
      this.$nextTick(() => {
        // 监听到事件后执行的业务逻辑
        this.chart.resize()
      })
    })
    this.chart.on('click', (params) => {
      this.$emit('callback', params)
    })
    this.loadData()
  },
  methods: {
    loadData() {
      if (undefined !== this.data) {
        this.chart.showLoading()
        this.data().then(res => {
          this.chart.hideLoading()
          console.log(res)
          this.localDataset = res
        })
      }
    }
  }
}
</script>
